/**
 * 
 */
package com.py.credit.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.py.credit.entity.common.TreeObj;

/**
 * @author dd
 *
 */
public class TreeUtils {

	public static List<TreeObj> getTree(List<TreeObj> dataList) {
		Map<String, TreeObj> cleanMap = new HashMap<String, TreeObj>();
		for (TreeObj r : dataList) {
			cleanMap.put(r.getId(), r);
		}
		// 过滤无法关联的数据
		List<TreeObj> cleanList = new ArrayList<TreeObj>();
		for (TreeObj vi : dataList) {
			if (isRelax(cleanMap, vi.getId())) {
				cleanList.add(vi);
			}
		}
		// 构造树结构
		List<TreeObj> resultList = getResult(cleanList);

		return resultList;
	}

	private static boolean isRelax(Map<String, TreeObj> cleanMap, String id) {
		if (cleanMap.containsKey(id)) {
			TreeObj node = cleanMap.get(id);
			if ("0".equals(node.getpId()) || null == node.getpId()) {
				return true;
			} else {
				return isRelax(cleanMap, node.getpId());
			}
		} else {
			return false;
		}
	}

	private static List<TreeObj> getResult(List<TreeObj> src) {
		List<TreeObj> parents = new ArrayList<TreeObj>();
		TreeObj result = null;
		for (TreeObj ent : src) {
			if ("0".equals(ent.getpId()) || null == ent.getpId()) {
				result = ent;
				result.setChildren(new ArrayList<TreeObj>());
				parents.add(result);
			}
		}
		List<TreeObj> last = new ArrayList<TreeObj>();
		for (TreeObj ent : src) {
			if (!"0".equals(ent.getpId()) && null != ent.getpId()) {
				last.add(ent);
			}
		}
		buildTree(parents, last);
		return parents;
	}

	private static void buildTree(List<TreeObj> parents, List<TreeObj> others) {
		List<TreeObj> record = new ArrayList<TreeObj>();
		TreeObj vi = null;
		TreeObj inVi = null;
		for (Iterator<TreeObj> it = parents.iterator(); it.hasNext();) {
			vi = it.next();
			if (vi.getId().equals(null) || !vi.getId().equals("0")) {
				for (Iterator<TreeObj> otherIt = others.iterator(); otherIt.hasNext();) {
					inVi = otherIt.next();
					if (vi.getId().equals(inVi.getpId())) {
						if (null == vi.getChildren()) {
							vi.setChildren(new ArrayList<TreeObj>());
						}
						vi.getChildren().add(inVi);
						record.add(inVi);
						otherIt.remove();
					}
				}
			}
		}
		if (others.size() == 0) {
			return;
		} else {
			buildTree(record, others);
		}
	}

}
